package com.zerosky.crm.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.News;
import com.zerosky.crm.service.NewsService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.MyFileUploadUtils;
import com.zerosky.crm.util.PageInfo;

/**
 * 新闻相关业务的Controller
 * 
 * @author 钟璟
 *
 */
@Controller
public class NewsController extends BaseAction {

	private Logger logger = LoggerFactory.getLogger(NewsController.class); // 日志

	@Resource(name = "newsService")
	private NewsService newsService;

	/**
	 * 跳转新闻界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toNews.do")
	public ModelAndView toNews(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/staging/newsList");
	}

	/**
	 * 跳转系统管理新闻界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toSystemNewsList.do")
	public ModelAndView toSystemNewsList(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		if (checkPower(session, 111)) {
			return new ModelAndView("WEB-INF/jsp/system/newsList");
		} else {
			return new ModelAndView("WEB-INF/jsp/error/404");
		}
	}

	/**
	 * 富文本图片上传
	 * 
	 * @param request
	 * @param response
	 * @param upload
	 * @return
	 */
	// @ResponseBody
	// @RequestMapping("/ckeditorUpload.do")
	// public String ImageUpload(HttpServletRequest request, HttpServletResponse
	// response,
	// @RequestParam("upload") MultipartFile upload) {
	// response.setContentType("text/html; charset=utf-8");
	// response.setContentType("application/json;charset=UTF-8");// 防止数据传递乱码
	// String callback = request.getParameter("CKEditorFuncNum");
	// String path = request.getSession().getServletContext().getRealPath("/") +
	// "saituImage/";
	// String imgName = "";
	// String json = ""; // 返回的json数据
	// /* 上传到服务器 */
	// try {
	//
	// File targetFile = new File(path);
	//
	// // 如过该文件夹不存在，则创建
	// if (!targetFile.exists()) {
	// targetFile.mkdirs();
	// }
	//
	// if (!upload.isEmpty()) {
	// // 获得文件类型（可以判断如果不是图片，禁止上传）
	// String uploadContentType = upload.getContentType();
	//
	// String expandedName = ""; // 文件扩展名
	// if (uploadContentType.equals("image/pjpeg") ||
	// uploadContentType.equals("image/jpeg")) {
	// //
	// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
	// expandedName = ".jpg";
	// } else if (uploadContentType.equals("image/png") ||
	// uploadContentType.equals("image/x-png")) {
	// // IE6上传的png图片的headimageContentType是"image/x-png"
	// expandedName = ".png";
	// } else if (uploadContentType.equals("image/gif")) {
	// expandedName = ".gif";
	// } else if (uploadContentType.equals("image/bmp")) {
	// expandedName = ".bmp";
	// } else {
	// json = "<script type=\"text/javascript\">" +
	// "window.parent.CKEDITOR.tools.callFunction(" + callback
	// + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');" + "</script>";
	// json = new String(json.getBytes(), "UTF-8");
	// return json;
	// }
	//
	// /*
	// * if(upload.length() > 600*1024){ out.println(
	// * "<script type=\"text/javascript\">");
	// * out.println("window.parent.CKEDITOR.tools.callFunction(" +
	// * callback + ",''," + "'文件大小不得大于600k');");
	// * out.println("</script>"); return null; }
	// */
	//
	// // 获取UUID和图片后缀=图片名
	// String uuid = UUID.randomUUID().toString().replace("-", "");
	// imgName = uuid + expandedName;
	// upload.transferTo(new File(path + imgName));
	//
	// /* 返回富文本 */
	// /*
	// * "http://" + request.getServerName() // 服务器地址 + ":" +
	// * request.getServerPort() // 端口号 + request.getContextPath() +
	// * "/
	// */
	// String url = "saituImage/" + imgName;
	//
	// json = "<script type=\"text/javascript\">" +
	// "window.parent.CKEDITOR.tools.callFunction(" + callback
	// + ",'" + url + "',''" + ")" + "</script>";
	// } else {
	// json = "<script type=\"text/javascript\">" +
	// "window.parent.CKEDITOR.tools.callFunction(" + callback
	// + ",''," + "'错误上传');" + "</script>";
	// }
	// } catch (Exception e) {
	// logger.error("获取数据失败，原因：" + e);
	// json = "<script type=\"text/javascript\">" +
	// "window.parent.CKEDITOR.tools.callFunction(" + callback
	// + ",''," + "'未知错误');" + "</script>";
	// }
	// return json;
	// }

	/**
	 * 获取新闻列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/newsList.do")
	@ResponseBody
	public Map<String, Object> NewsList(Integer limit, Integer page, String title, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		try {
			if (Strings.isNotEmpty(title)) {// 条件查询
				param.put("newsTitle", title);
			}
			param.put("pageNo", page);
			param.put("pageSize", limit);
			PageInfo<News> pageRole = newsService.getPageInfoNewsList(param);
			json.put("total", pageRole.getPageCount());
			json.put("data", pageRole.getList());
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;

	}

	/**
	 * 删除新闻信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delNews.do")
	@ResponseBody
	public Map<String, Object> delNews(Integer id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			if (newsService.deleteNews(id) > 0) {
				json.put("code", 0);
			} else {
				json.put("code", 1);
			}
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 请求编辑新闻信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/editNews.do")
	@ResponseBody
	public Map<String, Object> editNews(Integer id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			News news = newsService.getNewsById(id);
			if (news != null) {
				json.put("news", news);
				json.put("code", 0);
			} else {
				json.put("code", 1);
			}

		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 添加新闻信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertNews.do")
	@ResponseBody
	public Map<String, Object> insertNews(News news, String date1, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			news.setCreateDate(new Date());// 获取创建时间
			news.setReleaseDept(user.getDept().getDeptName());// 获取创建部门
			news.setCreateEmpId(user.getEmployeeId());// 获取创建人ID
			news.setCreatePeople(user.getName());// 获取创建人
			if (news.getHotelImgFile() != null&& (news.getNewsPicture()==null || news.getNewsPicture()=="")) {
				MyFileUploadUtils.saveFile(request, news.getHotelImgFile(), "saituImage/");
				if (request.getAttribute("picture") != null || news.getNewsPicture() == null) {
					String picture = "saituImage/" + (String) request.getAttribute("picture");
					news.setNewsPicture(picture);
				}
			}
			if (newsService.saveNews(news) > 0) {
				json.put("code", 0);
			} else {
				json.put("code", 1);
			}
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 修改新闻信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateNews.do")
	@ResponseBody
	public Map<String, Object> uodateNews(News news, String date1, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			// 时间转为date类型
			Date date = sf.parse(date1);
			news.setCreateDate(date);
			if (news.getHotelImgFile() != null && (news.getNewsPicture()==null || news.getNewsPicture()=="")) {
				MyFileUploadUtils.saveFile(request, news.getHotelImgFile(), "saituImage/");
				if (request.getAttribute("picture") != null || news.getNewsPicture() == null) {
					String picture = "saituImage/" + (String) request.getAttribute("picture");
					news.setNewsPicture(picture);
				}
			}
			if (newsService.updateNews(news) > 0) {
				json.put("code", 0);
			} else {
				json.put("code", 1);
			}
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}
}
